import os
import re

import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from pypac import PACSession, get_pac
import os
import zipfile


def unzip_file(src_file, dest_dir, *password):
    if password:
        password = password.encode()
    zf = zipfile.ZipFile(src_file)
    try:
        zf.extractall(path=dest_dir, pwd=password)
    except RuntimeError as e:
        print(e)
    zf.close()


def check_chrome_driver():
    # 获取项目根路径
    root_path = os.path.abspath(os.path.dirname(__file__)).replace("test", "")
    print("root_path", root_path)
    download_path = root_path + "download\\"  # 这里需要提前手动创建号download目录
    try:
        service = Service(root_path + "chromedriver.exe")
        driver = webdriver.Chrome(service=service)
    except Exception as msg:
        # print("ChromeWebDriver异常：" + str(msg))
        reg = "Current browser version is.+with"
        chrome_version = (
            re.search(reg, str(msg))
            .group()
            .replace("Current browser version is ", "")
            .replace(" with", "")
        )
        file_name = download_path + "chromedriver_" + chrome_version + ".zip"
        print("Chrome Version:" + chrome_version)

        url = (
            "http://chromedriver.storage.googleapis.com/"
            + chrome_version
            + "/chromedriver_win32.zip"
        )
        response = requests.get(url=url)

        # 使用代理
        # proxy = 'xxx.xxx.x.xx:8080'
        # proxies = {
        #     'http': 'http://' + proxy,
        #     'https': 'https://' + proxy
        # }
        # response = requests.get(url=url, proxies=proxies)

        # 使用PAC自动代理
        # pac = get_pac(url='http://xxx.xxx.x.xx:8080/xxx.pac')
        # pac_session = PACSession(pac)  # 解析pac文件
        # response = pac_session.get(url)

        # 保存ChromeDriver到当前项目路径下的/download目录下
        open(file_name, "wb").write(response.content)
        # 解压zip文件
        unzip_file(file_name, download_path)


check_chrome_driver()
